package org.logistics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.logistics.bean.MapInforBean;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
/**
 * 
 * @author yimou
 * 显示车辆列表
 *
 */
public class CarListActivity extends Activity {

	private String TAG = "org.logistics.carlist";
	private List<MapInforBean> mapInforList = new ArrayList<MapInforBean>() ;
	private ListView listView ;
	
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_list);
		
		//请求服务器得到车辆信息
		try {
			 getLocalPlace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		
		int len = mapInforList.size();
		for(int i = 0 ; i < len ; i++){
			MapInforBean mifb = new MapInforBean();
			mifb = mapInforList.get(i);
			String ifOnline = null;
			if(mifb.isOnLine() == false ){
				ifOnline = "离线";
			}if(mifb.isOnLine() == true){
				ifOnline = "在线";
			}

		    Map<String , Object> listItem = new HashMap<String, Object>();
		    listItem.put("car_num", mifb.getCarNum().trim());
		    listItem.put("car_information_1", ifOnline.trim() + "  " + mifb.getSpeed()+ "km/h"
					+ "  "+ mifb.getLocationTime().trim() );
		    listItem.put("car_information_2", mifb.getAddress().trim());
		    listItems.add(listItem);
		}
		SimpleAdapter  simpleAdapter = new SimpleAdapter(this , listItems ,
				R.layout.car_list_item , 
				new String[]{"car_num" ,"car_information_1" ,
						"car_information_2" } , 
						new int[]{R.id.car_num , R.id.car_information_1
				,R.id.car_information_2});
		listView = (ListView) findViewById(R.id.car_list);
		listView.setAdapter(simpleAdapter);
		
	}
  
	
 /**
   * 请求服务器获得数据 
   */
  public void getLocalPlace() throws JSONException, IllegalStateException, IOException{
	  BufferedReader in = null;
		/**
		 * 发送请求
		 */
		try {
			String request = "http://sj.jy100.com/GetRealtime2.ashx?userName=GPS4&address=true";
			HttpClient hc = new DefaultHttpClient();
			HttpPost hp = new HttpPost(request);
			HttpResponse response = hc.execute(hp);  
	        in = new BufferedReader(  
	                new InputStreamReader(  
	                        response.getEntity().getContent()));  
	        StringBuffer string = new StringBuffer("");  
	        String lineStr = "";  
	        while ((lineStr = in.readLine()) != null) {  
	            string.append(lineStr + "\n");  
	        }  
	        in.close();  
	        String resultStr = string.toString();  
	        Log.i(TAG, resultStr);
	        
	        /**
	         * 解析字符串
	         */
	        JSONObject jo = new JSONObject(resultStr);
	        
	        /**
	         * 得到数据条数
	         * TotalCount
	         */
	        int totalCount = jo.getInt("TotalCount");
	        Log.i(TAG, "共有"+totalCount+"条数据");
	        
	        /**
	         * 把解析数据转保存在对象
	         */
	        JSONArray jsonList = jo.getJSONArray("RootResults");
	        for(int i = 0 ; i < totalCount ; i++  )
	        {
	        	JSONObject temp = new JSONObject(jsonList.getString(i));
	        	MapInforBean mifb = new MapInforBean();
	        	mifb.setCarNum(temp.getString("A"));
	        	mifb.setiMei(temp.getString("D"));
	        	mifb.setOnLine(temp.getBoolean("F"));
	        	mifb.setLocationTime(temp.getString("G"));
	        	mifb.setH(temp.getDouble("H"));
	        	mifb.setI(temp.getDouble("I"));
	        	mifb.setAngle(temp.getInt("K"));
	        	mifb.setSpeed(temp.getInt("J"));
	        	mifb.setMileage(temp.getDouble("L"));
	        	mifb.setStatue(temp.getString("M"));
	        	mifb.setAddress(temp.getString("O"));
	        	mapInforList.add(mifb);
	        }
			
		} catch (JSONException e) {
			Log.i(TAG, e.getMessage());
		}finally {  
          if (in != null) {  
              try {  
                  in.close();  
              } catch (IOException e) {  
                  e.printStackTrace();  
              }  
          }  
      }
  };

  
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.car_list, menu);
		return true;
	}

}
